package com.bjsj.pro.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.bjsj.pro.base.view.NetworkLayout;
import com.bjsj.pro.base.view.TitleBarLayout;
import com.bjsj.pro.bean.LoginBean;
import com.bjsj.pro.tools.Configs;
import com.bjsj.pro.tools.GlideManager;
import com.bjsj.pro.tools.GlobalTools;
import com.bjsj.pro.tools.HandlerTools;
import com.lzy.okgo.OkGo;
import com.bjsj.pro.R;
import com.bjsj.pro.TourismApp;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * MVP模式抽象类Activity
 *
 * @author xiao 2017.03.11
 */
public abstract class MVPBaseActivity<V, T extends MVPBasePresenter<V>> extends AppCompatActivity
        implements HandlerTools.OnReceiveMessageListener
{
    private View mBaseView;
    // Presenter对象
    protected T mPresenter;
    protected MVPBaseActivity base;
    protected TitleBarLayout mTitleBarLayout;
    protected GlobalTools tools;
    protected NetworkLayout failnetworkd;;
    protected RefreshLayout mRefreshLayout;
    private ClassicsHeader mClassicsHeader;
    private Unbinder mUnbinder;
    protected GlideManager Gm;
    private View ll_title_bar_state;
    protected View viewStatus;
    protected HandlerTools.HandlerHolder baseHandler;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Gm = new GlideManager(this);
        base = this;
        tools = GlobalTools.getInstance();
        // 创建Presenter
        mPresenter = createPresenter();
        // View与Presenter建立关联
        mPresenter.attachView((V) this);
        TourismApp.getAppInstance().addActivity(this);

        initAll();
    }

    private void initAll()
    {
        View view = LayoutInflater.from(this).inflate(R.layout.activity_base, null, false);
        initChildView(view);
        setContentView(view);
        baseHandler = new HandlerTools.HandlerHolder(this);
        initData();
        initView();

    }

    private void initChildView(View mBaseView)
    {
        mTitleBarLayout = mBaseView.findViewById(R.id.tlb_base_titlebar);
        failnetworkd =  mBaseView.findViewById(R.id.failnetworkd);
        //继承StoreBaseActivity的Activity不设置新接口回调监听默认就是finish();
        mTitleBarLayout.setmOnLefeListener(new TitleBarLayout.OnLefeListener()
        {
            @Override
            public void onLefeLinstener()
            {
                finish();

            }
        });
        FrameLayout mBaseFrameLayout = (FrameLayout) mBaseView.findViewById(R.id.fl_base_jump_bottom);
        //绑定子view
        mBaseFrameLayout.addView(addChildView(mBaseFrameLayout, setLayoutResId()));
        //上下拉刷新控件
        mRefreshLayout = mBaseView.findViewById(R.id.refreshLayout);
        mClassicsHeader = mBaseView.findViewById(R.id.header);
      //  ll_title_bar_state = mBaseView.findViewById(R.id.ll_title_bar_state);
        tools.initRefreshLayout(mRefreshLayout,false,false);
        //状态栏高度
        viewStatus = mBaseView.findViewById(R.id.viewStatus);
        ViewGroup.LayoutParams layoutParams = viewStatus.getLayoutParams();
        layoutParams.height=tools.getStatusBarHeight(base);
        viewStatus.setLayoutParams(layoutParams);
        viewStatus.setLayoutParams(layoutParams);
    }

    private View addChildView(FrameLayout fragmentview, int layoutResId)
    {
        mBaseView = LayoutInflater.from(this).inflate(layoutResId, fragmentview, false);
        mUnbinder = ButterKnife.bind(this, mBaseView);
        return mBaseView;
    }
    protected void setprogressdrawable(int res){
    mClassicsHeader.setProgressResource( res);
    }
    /**
     * 设置全屏沉浸模式显示，不要状态栏跟标题栏
     **/
    protected void setFullScreen()
    {
        hideFlmTitleBarLayout();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    /**
     * 构造方法描述:使findViewById不需要再强转
     */
    protected <T extends View> T BaseFindView(int resId)
    {
        return (T) (findViewById(resId));
    }

    protected void hideFlmTitleBarLayout()
    {
        mTitleBarLayout.setVisibility(View.GONE);
    }

    protected void showTitleBarLayout(boolean stats, String title, String leftString,int color)
    {
        mTitleBarLayout.setVisibility(View.VISIBLE);
        mTitleBarLayout.setLefeShow(true, R.drawable.xiang_zuo_icon, leftString);
        mTitleBarLayout.setTitle(title);
        if(color!=0){
            mTitleBarLayout.setLefeShow(true,color, leftString);
        }
        if (stats)
        {
            showStatusView(stats);
            getWindow().getDecorView().setSystemUiVisibility
                    (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
    }

    protected void showStatusView(boolean isShowStatus)
    {
        if(isShowStatus)
        {
            setStatusTextColor();
            viewStatus.setVisibility(View.VISIBLE);
        }
        else {
            viewStatus.setVisibility(View.GONE);
        }
    }

    protected void setStateColor(int color)
    {
        viewStatus.setBackgroundColor(color);
    }
    //设置状态栏文字颜色及图标为深色
    protected void setStatusTextColor()
    {
        //状态栏字体颜色加深
        getWindow().getDecorView().
                setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN );//| View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    }
    /**
     * 创建泛型的Presenter
     *
     * @return
     */
    protected abstract T createPresenter();

    /**
     * 子类实现设置布局layout
     *
     * @return view
     */
    protected abstract int setLayoutResId();
//    protected abstract View setLayoutResId();

    protected abstract void initData();

    protected abstract void initView();


    /**
     * 解除关联
     */
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (mPresenter.isViewAttached())
        {
            mPresenter.detachView();
        }
        OkGo.getInstance().cancelTag(this);
        //当前Activity页面所有的请求以Activity对象作为tag，可以在onDestory里面统一取消。
        if (mUnbinder != null)
        {
            mUnbinder.unbind();
        }

        if (baseHandler != null)
        {
            baseHandler.removeCallbacksAndMessages(null);
        }

    }

    @Override
    public void handlerMessage(Message msg)
    {

    }

    private OnBaseLifeCallBack mOnBaseLifeCallBack;

    public void setmOnBaseCallBack(OnBaseLifeCallBack mOnBaseLifeCallBack)
    {
        this.mOnBaseLifeCallBack = mOnBaseLifeCallBack;
    }

    public interface OnBaseLifeCallBack
    {
        void OnlifeCallBack();

        void OnRightCallBack();
    }
    public void showStatus()
    {
        ll_title_bar_state.setVisibility(View.VISIBLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        }
    }
    /***
     * 登录过期提示对话框
     * */
    protected void showOpenLoginDialog()
    {
        new AlertDialog.Builder(this).setTitle("提示").setMessage("登录已过期，是否重新登录?")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i)
                    {
                        //销毁所有界面跳转到登录
                        TourismApp.getAppInstance().exitApp();
                        // startActivity(new Intent(base, LoginActivity.class));
                    }
                })
                .show();
    }

    protected  String getToken()
    {
        LoginBean userInfo = (LoginBean) tools.readObject(base, Configs.SAVE_LOGIN_KEY, Configs.SAVE_LOGIN_SP_NAME);
        if (userInfo != null)
        {
            Log.d("ccccccccccc",userInfo.getData().getToken());
            return userInfo.getData().getToken();
        } else
        {
            return "";
        }
    }

   /* protected personxinxi getUserInfo()
    {
        LoginBean userInfo = (LoginBean) tools.readObject(base, Configs.SAVE_LOGIN_KEY, Configs.SAVE_LOGIN_SP_NAME);
        if (userInfo != null)
        {
            return userInfo.getData();
        } else
        {
            return null;
        }
    }*/

    protected LoginBean getUserInfo()
    {
        LoginBean userInfo = (LoginBean) tools.readObject(base, Configs.SAVE_LOGIN_KEY, Configs.SAVE_LOGIN_SP_NAME);
        if (userInfo != null)
        {
            return userInfo;
        } else
        {
            return null;
        }
    }

    /**
     * 获取本地软件版本号​
     */
    public static int getLocalVersion(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
            Log.d("TAG", "当前版本号：" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }


    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;
            Log.d("TAG", "当前版本名称：" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }


}
